<?php

namespace SinoPHP\BbdBoss\Api;

use ErrorException;
use InvalidArgumentException;
use SinoPHP\BbdBoss\Library\AppAuth;
use SinoPHP\BbdBoss\Library\JwtHelper;
use SinoPHP\BbdBoss\Model\AppAccount;

/**
 * APP应用鉴权
 *
 * Params:
 *      data:appId      (string)    APP应用ID
 *      data:signature  (string)    加密签名
 */
class Auth extends ApiAbstract {

    /**
     * AppAccount Model
     *
     * @var AppAccount
     */
    protected $appAccount;

    public function v_1_0_0() {
        $this->appAccount = model('AppAccount');
        $appAuth = new AppAuth();
        $params = $this->requestParams;

        if (empty($params['appId']) || strlen($params['appId']) != 16) {
            throw new InvalidArgumentException('', 101006);
        }

        // signature
        if (empty($params['signature'])) {
            throw new InvalidArgumentException('', 101007);
        }

        // 验证应用是否存在
        $appInfo = $this->appAccount->getRow('*', ['app_id' => $params['appId']]);
        if (!$appInfo) {
            throw new ErrorException('应用不存在', 101008);
        }

        // 校验签名
        $systemSign = $appAuth->signature($params['appId'], $appInfo['secret'], $appInfo['encoding_key']);
        if ($params['signature'] != $systemSign) {
            throw new ErrorException('', 101009);
        }

        $expires = 7200;
        $contents = array(
            'app_id' => $appInfo['app_id'],
            'app_name' => $appInfo['app_name'],
        );

        $data = array(
            'token' => (string) JwtHelper::buildToken($appInfo['secret'], $params['appId'], $contents, $expires),
            'expires' => $expires,
        );

        // 成功, 返回success; 失败, 返回状态码+错误提示
        $this->success($data);
    }

}
